package repositories

import (
	database "web2/pkg/db"
	"web2/pkg/models"

	"gorm.io/gorm"
)

type ProductRepository interface {
	FindAll() ([]models.Product, error)
	FindByID(id uint) (*models.Product, error)
	Create(product *models.Product) error
	Update(id uint, product *models.Product) error
	Delete(id uint) error
}

type productRepository struct {
	db *gorm.DB
}

func NewProductRepository() ProductRepository {
	return &productRepository{
		db: database.GetDB(),
	}
}

func (r *productRepository) FindAll() ([]models.Product, error) {
	var products []models.Product
	result := r.db.Find(&products)
	return products, result.Error
}

func (r *productRepository) FindByID(id uint) (*models.Product, error) {
	var product models.Product
	result := r.db.First(&product, id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &product, nil
}

func (r *productRepository) Create(product *models.Product) error {
	result := r.db.Create(product)
	return result.Error
}

func (r *productRepository) Update(id uint, product *models.Product) error {
	result := r.db.Model(&models.Product{}).Where("id = ?", id).Updates(product)
	return result.Error
}

func (r *productRepository) Delete(id uint) error {
	result := r.db.Delete(&models.Product{}, id)
	return result.Error
}
